package com.gx.smart.building.ui.repair.fragment

import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.ViewGroup
import androidx.navigation.fragment.findNavController
import com.blankj.utilcode.util.ToastUtils
import com.gx.smart.base.BaseMVVMFragmentV2
import com.gx.smart.building.R
import com.gx.smart.building.databinding.FragmentProcessingBackBinding
import com.gx.smart.building.ui.repair.viewmodel.RepairViewModel


class ProcessingBackFragment : BaseMVVMFragmentV2<RepairViewModel>() {
    private lateinit var viewBinding: FragmentProcessingBackBinding
    override fun onBindLayout(): Int = R.layout.fragment_processing_back

    override fun getToolbarTitle(): String = "工单退回"

    override fun onBindViewModel(): Class<RepairViewModel> = RepairViewModel::class.java

    override fun initContentView(root: ViewGroup) {
        viewBinding = FragmentProcessingBackBinding.inflate(layoutInflater, root, true)
    }

    override fun initContent() {
        super.initContent()
        viewBinding.contentEdit.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
            override fun afterTextChanged(s: Editable) {
                viewBinding.wordCount.text = s.length.toString() + "/200"
            }
        })

        viewBinding.save.setOnClickListener {
            save()
        }

        //标签的点击监听
        viewBinding.labels.setOnLabelClickListener { label, data, position -> //label是被点击的标签，data是标签所对应的数据，position是标签的位置。
            viewBinding.contentEdit.editableText.clear()
            viewBinding.contentEdit.setText(data as? String)
        }
    }

    override fun initData() {
        viewModel.queryWorkOrderEventOpinionSettingList("back_task")
            .observe(viewLifecycleOwner) { list ->
                viewBinding.labels.setLabels(list.map { item -> item.opinion })
            }
    }

    private fun save() {
        val suggestion = viewBinding.contentEdit.text.toString().trim()
        if (suggestion.isNullOrEmpty()) {
            ToastUtils.showLong("请填写回退意见")
            return
        }

        viewModel.backTask(requireArguments().getString("id")!!, suggestion)
            .observe(viewLifecycleOwner) {
                if (it) {
                    findNavController().navigate(R.id.action_processingBackFragment_to_repairResultFragment,
                        Bundle().apply {
                            putString("type", "back")
                        }
                    )
                }
            }
    }
}